package com.chuangyang.fixboxmaster.ui;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;

import com.android.volley.Response;
import com.chuangyang.fixboxlib.widgets.PullDownRefreshListView;
import com.chuangyang.fixboxlib.widgets.PullDownRefreshSwipeListView;
import com.chuangyang.fixboxmaster.R;
import com.chuangyang.fixboxmaster.bean.Message;
import com.chuangyang.fixboxmaster.service.FixBoxApi;
import com.chuangyang.fixboxmaster.service.GsonRequest;
import com.chuangyang.fixboxmaster.ui.adapter.MessageAdapter;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * Created by vanshu on 15/8/25 10:16.
 */
public class MessageCenterActivity extends BaseActivity  implements AdapterView.OnItemClickListener, PullDownRefreshSwipeListView.OnRefreshListener{
    private PullDownRefreshListView mListView;
    private MessageAdapter mMessageAdapter;
    private ArrayList<Message> messageArrayList=new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("消息中心");
        mMessageAdapter=new MessageAdapter(this,messageArrayList);
        setContentView(R.layout.activity_message_center);
        mListView= (PullDownRefreshListView) findViewById(R.id.listview);
        mListView.setAdapter(mMessageAdapter);
        mListView.setOnItemClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        messageArrayList.clear();
        mMessageAdapter.notifyDataSetChanged();
        loadData();

    }

    private Response.Listener<Message.MessageInfo> responseListener=new Response.Listener<Message.MessageInfo>() {
        @Override
        public void onResponse(Message.MessageInfo response) {
            if(response.result!=null){
                messageArrayList.addAll(Arrays.asList(response.result.list));
                mMessageAdapter.notifyDataSetChanged();
                if (messageArrayList.size()>= response.result.total)
                    mListView.setLoadingEnd();
                else
                    mListView.setLoadingIdle();
            }
        }
    };


    public void loadData() {
        mListView.setLoading();
        addRequest(new GsonRequest<>(FixBoxApi.GET_MY_MESSAGE, Message.MessageInfo.class, responseListener));
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(this, MessageDetailActivity.class);
        intent.putExtra("message",messageArrayList.get(position));
        startActivity(intent);
    }

    @Override
    public void onRefresh() {
        loadData();
    }
}
